package com.tsj.spzx.controller;

import com.tsj.spzx.utils.AuthContextThreadLocalUtil;
import com.tsj.spzx.model.dto.system.LoginDto;
import com.tsj.spzx.model.entity.system.SysUser;
import com.tsj.spzx.model.vo.common.Result;
import com.tsj.spzx.model.vo.common.ResultCodeEnum;
import com.tsj.spzx.model.vo.system.LoginVo;
import com.tsj.spzx.model.vo.system.SysMenuVo;
import com.tsj.spzx.model.vo.system.ValidateCodeVo;
import com.tsj.spzx.service.SysMenuService;
import com.tsj.spzx.service.SysUserService;
import com.tsj.spzx.service.ValidateCodeService;
import io.swagger.v3.oas.annotations.Operation;
import org.junit.jupiter.api.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@CrossOrigin(allowCredentials = "true" , originPatterns = "*" , allowedHeaders = "*")
@RestController
@Tag("用户接口")
@RequestMapping("/admin/system/index")
public class IndexController {

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private ValidateCodeService validateCodeService;
    @Autowired
    private SysMenuService sysMenuService;

    @Operation(summary = "用户登录")
    @PostMapping("/login")
    public Result<LoginVo> login(@RequestBody LoginDto loginDto) {
        // System.out.println(loginDto.toString());
        LoginVo loginVo = sysUserService.login(loginDto);
        return Result.build(loginVo, ResultCodeEnum.SUCCESS);
    }

    @Operation(summary = "获取验证码")
    @GetMapping("/generateValidateCode")
    public Result<ValidateCodeVo> getValidateCode() {
        ValidateCodeVo validateCodeVo = validateCodeService.getValidateCode();
        return Result.build(validateCodeVo, ResultCodeEnum.SUCCESS);
    }

//    @Operation(summary = "根据token获取用户信息")
//    @GetMapping("/userinfo")
//    public Result<SysUser> getUserInfoByToken(@RequestHeader("token") String token) {
//        SysUser sysUser = sysUserService.getUserInfoByToken(token);
//        return Result.build(sysUser, ResultCodeEnum.SUCCESS);
//    }

    /**
     * 有了拦截器后，我们将用户信息存入了ThreadLocal中，所以这里直接从ThreadLocal中获取用户信息
     * @return
     */
    @Operation(summary = "根据token获取用户信息")
    @GetMapping("/userinfo")
    public Result<SysUser> getUserInfoByToken() {
        return Result.build(AuthContextThreadLocalUtil.get(), ResultCodeEnum.SUCCESS);
    }

    @Operation(summary = "用户退出")
    @GetMapping("/logout")
    public Result logout(@RequestHeader("token") String token) {
        sysUserService.logout(token);
        return Result.build(null, ResultCodeEnum.SUCCESS);
    }


    /**
     * 根据用户id动态获取菜单
     * @return
     */
    @GetMapping("/menus")
    public Result menus(){
        List<SysMenuVo> userMenuList =sysMenuService.getMenusByUserId();
        return Result.build(userMenuList, ResultCodeEnum.SUCCESS);
    }

}
